<?php

require_once("../../controllers/init.php");
require_once($FILE_SYSTEM_ROOT."/controllers/authentication.php");
// echo "IS_LOGGED_ON = ".$GLOBALS['IS_LOGGED_ON'];
require_once($FILE_SYSTEM_ROOT."/model/classes/events/SNAPEvent.php");

if(!$GLOBALS['IS_LOGGED_ON'])
{
	echo "ERROR_NOT_LOGGED_ON";
	exit;
}

//echo $_POST['action'];
switch ($_POST['action'])
{
	case 'insert':
		
		$event = new SNAPEvent(-1); // create an empty event object
		$event->loadFromPOST();
		$insertdate = $event->getStart();
		if(isset($_POST['repeatuntil']))
			$repeatUntil = new DateTime($_POST['repeatuntil']);
		else 
			$repeatUntil = new DateTime($event->getStart());
		$repeatUntil->setTime(23,59); // set to the end of the day

		if(isset($_POST['repeatevery']))
			$repeatEvery = $_POST['repeatevery'];
		else
			$repeatEvery = 'week';
		if ($repeatEvery == 'day') $interval = new DateInterval('P1D');
		if ($repeatEvery == 'week') $interval = new DateInterval('P1W');
		if ($repeatEvery == 'month') $interval = new DateInterval('P1M');
		$start = new DateTime($event->getStart());
		$end = new DateTime($event->getEnd());
		while($start<=$repeatUntil)
		{
			echo $event->insertAsNew();
			$start->add($interval);
			$event->setStart($start->format("Y-m-d H:i"));
			$end->add($interval);
			$event->setEnd($end->format("Y-m-d H:i"));
		}
		break;
		
	case 'update':
		$event = new SNAPEvent(-1); // create an empty event object
		$event->loadFromPOST();
		$insertdate = $event->getStart();
		if(isset($_POST['repeatuntil']))
			$repeatUntil = new DateTime($_POST['repeatuntil']);
		else 
			$repeatUntil = new DateTime($event->getStart());
		$repeatUntil->setTime(23,59); // set to the end of the day

		if(isset($_POST['repeatevery']))
			$repeatEvery = $_POST['repeatevery'];
		else
			$repeatEvery = 'week';
		if ($repeatEvery == 'day') $interval = new DateInterval('P1D');
		if ($repeatEvery == 'week') $interval = new DateInterval('P1W');
		if ($repeatEvery == 'month') $interval = new DateInterval('P1M');
		$start = new DateTime($event->getStart());
		$end = new DateTime($event->getEnd());
		$haveUpdated = false; // update first time - then insert
		while($start<=$repeatUntil)
		{
			if ($haveUpdated==true)
			{
				echo $event->insertAsNew();
				echo "Insert as new\n";
			}
			else
			{
				echo $event->update();
				echo "Update\n";
			}
			$haveUpdated = true;
			$start->add($interval);
			$event->setStart($start->format("Y-m-d H:i"));
			$end->add($interval);
			$event->setEnd($end->format("Y-m-d H:i"));
		}
		break;
		
	case 'delete':
		$event = new SNAPEvent($_POST['eventid']); 
		$event->delete();
//		echo $event->getEventID()." / ".$event->getTitle();
					
		break;

		
}
	

